package com.ssmShiro.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ssmShiro.entity.User;
import com.ssmShiro.entity.dto.PageInfo;
import com.ssmShiro.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserService userService;
	@RequestMapping(value="/login",method= RequestMethod.GET)
	public String login() throws Exception {
		return "/user/login";
	}
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(HttpServletRequest request ,User user)throws Exception{
		if(StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPassword())){
			request.setAttribute("msg", "用户名或没有不能为空");
			return "/user/login";
		}
		Subject subject=SecurityUtils.getSubject();
		UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());
		try {
			subject.login(token);
			return "index";
		} catch (LockedAccountException e) {
			token.clear();
			request.setAttribute("msg", "用户已经被锁定不能登录，请与管理员联系！");
			return "/user/login";
		}catch (AuthenticationException ae) {
			request.setAttribute("msg", "用户名或密码不正确!");
			return "/user/login";
		}
	}
	@RequestMapping("/list")
	@ResponseBody
	public List<User>list(User entity)throws Exception{
		return userService.getList(entity); 
	}
	
	@RequestMapping("/pageList")
	@ResponseBody
	public PageInfo<User>list(PageInfo<User>page,User entity)throws Exception{
		return userService.selectByPage(page, entity); 
	}
}
